#import "UpdateManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"

@implementation UpdateManager

SYNTHESIZE_SINGLETON_FOR_CLASS(UpdateManager);

-(id)init{
    self = [super init];
    curVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
    isChecking = NO;
    isFingerAction = NO;
    newVersion = @"";
    newVersionNotice = @"";
    hasNewVersion = NO;
    isUpdate = NO;
    isForceUpdate = NO;
    owner = nil;
    return self;
}

-(void) dealloc {
    PP_RELEASE(curVersion);
    PP_RELEASE(newVersion);
    PP_RELEASE(newVersionNotice);
    PP_RELEASE(owner);
    [super dealloc];
}

-(void)checkVersion:(BOOL)pIsFingerAction :(BaseUIViewController *)pOwner {
    if(isChecking){
        return;
    }
    isChecking = YES;
    isFingerAction = pIsFingerAction;
    newVersion = @"";
    newVersionNotice = @"";
    hasNewVersion = NO;
    isForceUpdate = NO;
    isUpdate = NO;
    owner = pOwner;
    //创建一个NSThread
    [NSThread detachNewThreadSelector:@selector(checking) toTarget:self withObject:nil];
}

//执行方法
- (void)checking
{
//    NSString *url = [NSString stringWithFormat:@"http://lengxiaohua.com/lengxiaohuaapi/app?client=iphone&action=getVersion"];
    NSString *url = APP_UPDATE_URL;
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    request.userAgentString = userAgentValue;
    [request setRequestMethod:@"GET"];
    [request setAllowCompressedResponse:YES];
    [request setUseCookiePersistence:YES];
    [request setDelegate:self];
    [request startSynchronous];
    NSError *error = [request error];
    if(!error){
        [self requestCheckDone:request];
    }else{
        [self requestCheckFailed:request];
    }
    //回到主线程
    [self performSelectorOnMainThread:@selector(showing:) withObject:newVersionNotice waitUntilDone:NO];
    isChecking = NO;
}

- (void)requestCheckDone:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    Log(@"res: %@",tResponseStr);
    
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    
    //json解析错误
    if (![tJsonObjects isKindOfClass:[NSDictionary class]]){
        Log(@"json err");
        return;
    }
    
    newVersion = [(NSDictionary *)tJsonObjects objectForKey:@"version"];
    Log(@"curVersion:%@ newVersion:%@",curVersion,newVersion);
    NSArray  * curVersionArray = [curVersion componentsSeparatedByString:@"."];
    NSArray  * newVersionArray = [newVersion componentsSeparatedByString:@"."];
    if(curVersionArray.count!=3||newVersionArray.count!=3){
        Log(@"version err");
        return;
    }
    hasNewVersion = NO;
    for(int i=0;i<3;++i){
        if([[newVersionArray objectAtIndex:i] integerValue]>[[curVersionArray objectAtIndex:i] integerValue]){
            hasNewVersion = YES;
            break;
        }
    }
    isUpdate = [[(NSDictionary *)tJsonObjects objectForKey:@"update"] boolValue];
    isForceUpdate = [[(NSDictionary *)tJsonObjects objectForKey:@"force_update"] boolValue];
    newVersionNotice = [NSString stringWithFormat:@"%@",[(NSDictionary *)tJsonObjects objectForKey:@"update_notice"]];
    
    Log(@"hasNewVersion:%@ isUpdate:%@ isForceUpdate:%@ newVersionNotice:%@",hasNewVersion?@"YES":@"NO",isUpdate?@"YES":@"NO",isForceUpdate?@"YES":@"NO",newVersionNotice);
}


- (void)requestCheckFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    Log(@"failed: %@",[error description]);
}

//主线程提示消息
- (void)showing:(NSString*)msg {
    if( !hasNewVersion || !isUpdate){
        if(isFingerAction){
            [owner baseShowInfoHud:NSLocalizedString(@"当前已经是最新版本", @"") andIsTop:NO];
        }else{
            //
        }
        return;
    }
    
    //需要更新
    if(isForceUpdate){
        if(isFingerAction){
            //
        }else{
            UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:@"发现重要更新" message:@"必须升级程序才能够正常运行" delegate:self cancelButtonTitle:@"马上更新" otherButtonTitles:@"还是更新吧",nil] autorelease];
            alert.tag = 1;
            [alert show];
            return;
        }
    }
    
    //需要更新,但不强制
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString *updateTime = [defaults stringForKey:@"updateTime"];
    if(isFingerAction){
        [self writeUpdateTime:currentTime];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"发现新版本" message:msg delegate:self cancelButtonTitle:@"马上更新" otherButtonTitles:@"以后再说",nil];
        alert.tag = 2;
        [alert show];
        [alert release];
        return;
    }
    
    //自动检测发现需要更新,但不强制
    Log(@"last showing time: %@ , current time: %@",updateTime,currentTime);
    if ([updateTime isEqualToString:currentTime]) {
        Log(@"already shown in 1 day");
        return;
    }else{
        Log(@"beyond 1 day, showing");
        [self writeUpdateTime:currentTime];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"发现新版本" message:msg delegate:self cancelButtonTitle:@"马上更新" otherButtonTitles:@"以后再说",nil];
        alert.tag = 2;
        [alert show];
        [alert release];
    }
}

#pragma --------alert操作----------
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int aT = alertView.tag;
    int bI = buttonIndex;
    if(aT == 1){
        switch (bI) {
            case 0:
                [owner presentAppStoreForID:[NSNumber numberWithInt:569068376] inView:nil withDelegate:owner withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", @"http://itunes.apple.com/cn/app/ai-jiang-leng-xiao-hua/id569068376?ls=1&mt=8"]]];
                break;
            case 1:
                //退出程序
                [owner presentAppStoreForID:[NSNumber numberWithInt:569068376] inView:nil withDelegate:owner withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", @"http://itunes.apple.com/cn/app/ai-jiang-leng-xiao-hua/id569068376?ls=1&mt=8"]]];
//                [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
                break;
            default:
                break;
        }
    } else if(aT == 2){
        switch (bI) {
            case 0:
                [owner presentAppStoreForID:[NSNumber numberWithInt:569068376] inView:nil withDelegate:owner withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", @"http://itunes.apple.com/cn/app/ai-jiang-leng-xiao-hua/id569068376?ls=1&mt=8"]]];
                break;
            case 1:
                break;
            default:
                break;
        }
    }
}

-(void)writeUpdateTime:(NSString*)updateTime
{
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject:updateTime forKey:@"updateTime"];
}


@end
